<template>
  <div class="patientTrack-container">
    <div class="el-descriptions__header">
      <div class="el-descriptions__title">患者数据</div>
    </div>
    <el-menu
      :default-active="activeIndex"
      mode="horizontal"
      @select="handleSelect"
    >
      <el-menu-item index="1">呼气峰流速值</el-menu-item>
      <el-menu-item index="2">用药打卡记录</el-menu-item>
      <el-menu-item index="3">视频采集</el-menu-item>
      <el-menu-item index="4">呼吸音采集</el-menu-item>
      <el-menu-item index="5">哮喘控制评估</el-menu-item>
    </el-menu>
    <!-- 呼吸峰流速 -->
    <div class="emrChart-content" v-if="activeIndex === '1'">
      <div class="hubs">
        <el-radio-group v-model="radioActive" @change="chartTypeChange">
          <el-radio-button label="列表"></el-radio-button>
          <el-radio-button label="图表"></el-radio-button>
        </el-radio-group>
        <XmDatePicker
          v-if="radioActive === '图表'"
          type="daterange"
          v-model="timeRang"
          disabledDateT="after"
          label="选择开始时间:"
          prop="fillingTime"
          style="flex: 1"
          :config="{ clearable: false }"
          @timeChange="timeChange"
        ></XmDatePicker>
        <div v-else style="flex: 1"></div>
        <el-button type="primary" @click="record">记录</el-button>
      </div>
      <template v-if="radioActive === '列表'">
        <el-table
          :data="pageData.listData"
          :header-cell-style="{ background: '#F5F5F5', 'text-align': 'center' }"
          :cell-style="{ 'text-align': 'center' }"
        >
          <XMTableColumn prop="submitTime" label="测试时间"></XMTableColumn>
          <XMTableColumn prop="type" label="状态">
            <template #default="scope">
              {{ scope.row.type === 1 ? '早间' : '晚间' }}
            </template>
          </XMTableColumn>
          <XMTableColumn prop="maxPef" label="最大值PEF(L/Min)"></XMTableColumn>
          <XMTableColumn prop="forecast" label="预测值">
            <template #header>
              <span>预测值</span>
              <el-popover placement="top-start" :width="200" trigger="hover">
                <div>
                  <div>男童计算规则：PEFR(升/分)=5.29x身高(cm)-427.1</div>
                  <div>女童计算规则：PEFR(升/分)=4.94x身高(cm)-399.8</div>
                </div>
                <template #reference>
                  <el-icon><InfoFilled /></el-icon>
                  <!-- <el-button>Hover to activate</el-button> -->
                </template>
              </el-popover>
            </template>
          </XMTableColumn>
        </el-table>
        <xm-pagination
          :total="pageData.total"
          @pagination="paginaChange"
        ></xm-pagination>
      </template>
      <div v-else style="width: 100%; height: 300px; text-align: center">
        <xm-line-chart
          v-if="pageData.chartData"
          :chartData="pageData.chartData"
          :legendData="['上午', '下午', '日间变异率(%)']"
        ></xm-line-chart>
        <div style="color: #909399; line-height: 60px">暂无数据</div>
      </div>
    </div>
    <!-- 行动日历打卡 -->
    <medication-record
      :pid="pageData.search.patientId"
      v-if="activeIndex === '2'"
    ></medication-record>
    <video-uploadlist
      v-if="activeIndex === '3'"
      type="video"
    ></video-uploadlist>
    <video-uploadlist v-if="activeIndex === '4'" type="BS"></video-uploadlist>
    <asthma-questionnaire
      v-if="activeIndex === '5'"
      :pid="pageData.search.patientId"
    ></asthma-questionnaire>
    <!-- <asthmaQuestionnaire></asthmaQuestionnaire> -->
    <el-dialog
      width="30%"
      title="呼气峰流速值"
      v-model="isVisble"
      @closed="() => dialogRef.resetFields()"
    >
      <el-form
        label-width="140px"
        :rules="rules"
        :model="pageData.form"
        ref="dialogRef"
      >
        <xm-f-picker
          type="datetime"
          disabledDateT="after"
          v-model="pageData.form.submitTime"
          label="测量时间:"
          prop="submitTime"
        ></xm-f-picker>
        <el-form-item prop="pef1" label="第一次测试:">
          <el-input v-model="pageData.form.pef1"></el-input>
        </el-form-item>
        <el-form-item prop="pef2" label="第二次测试:">
          <el-input v-model="pageData.form.pef2"></el-input>
        </el-form-item>
        <el-form-item prop="pef3" label="第三次测试:">
          <el-input v-model="pageData.form.pef3"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="isVisble = false">取 消</el-button>
          <el-button type="primary" @click="onSubmit">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script>
  import { ref, reactive, onMounted } from 'vue'
  import medicationRecord from './medicationRecord.vue'
  import videoUploadlist from './videoUploadlist.vue'
  // eslint-disable-next-line max-len
  import asthmaQuestionnaire from '@/views/reception/components/asthmaQuestionnaire.vue'
  import moment from 'moment'
  import {
    loadPefHistory,
    getPefChartData,
    savePef,
    getInitPef,
  } from '@/api/modules/patient'
  import { useRoute } from 'vue-router'
  import { ElMessage, ElLoading } from 'element-plus'
  import { InfoFilled } from '@element-plus/icons-vue'
  import { usePromise } from '@/hooks/core/usePromise'
  import XmDatePicker from '../../../components/XMC/XmDatePicker/index.vue'
  export default {
    components: {
      medicationRecord,
      videoUploadlist,
      asthmaQuestionnaire,
      InfoFilled,
      XmDatePicker,
    },
    setup() {
      const route = useRoute()
      function initActiveIndex() {
        if (route.query.anchorType === 'markCard') {
          return ref('2')
        }
        return ref('1')
      }
      const activeIndex = initActiveIndex()
      const radioActive = ref('列表')
      const isVisble = ref(false)
      const dialogRef = ref(null)
      // const getCardStatus = function (i) {

      // }
      const handleSelect = function (type) {
        activeIndex.value = type
      }

      const dateTo = moment().format('YYYY-MM-DD')
      const dateFrom = moment().subtract(7, 'd').format('YYYY-MM-DD')
      const timeRang = ref([dateFrom, dateTo])

      const pageData = reactive({
        listData: [],
        total: null,
        search: {
          patientId: route.query.id,
          pageIndex: 1,
          pageSize: 5,
          type: activeIndex.value,
          start: dateFrom,
          end: dateTo,
        },
        form: { submitTime: '', pef1: null, pef2: null, pef3: null },
        chartData: null,
      })
      const record = function () {
        isVisble.value = true
      }

      onMounted(() => {
        loadData(pageData.search)
      })
      const loadData = async function (params) {
        const res = await loadPefHistory(params)
        pageData.listData = res.data.map((item) => {
          item.value = item.startValue

          if (params.type === '6') {
            item.value = item.startValue + '~' + item.endValue
          }
          item.submitTime = moment(item.submitTime).format('YYYY-MM-DD HH:mm')
          return item
        })
        pageData.total = res.total
      }

      function timeChange(val) {
        loadPefCharData(pageData.search, val[0], val[1])
      }
      const loadPefCharData = async function (params, start, end) {
        params.startTime = moment(start ? start : pageData.search.start).format(
          'YYYY-MM-DD'
        )
        params.endTime = moment(end ? end : pageData.search.end).format(
          'YYYY-MM-DD'
        )
        const res = await getPefChartData(params)
        let xAxis = [],
          startValue = [],
          endValue = [],
          dvValue = [],
          tmp = []
        if (res.data && res.data.am && Array.isArray(res.data.am)) {
          res.data.am.forEach((item) => {
            tmp[item.fillDay] = { am: item.maxPef }
            // xAxis.push(item.fillDay)
            // startValue.push(item.maxPef)
          })
        }
        if (res.data && res.data.pm && Array.isArray(res.data.pm)) {
          res.data.pm.forEach((item) => {
            // endValue.push(item.maxPef)
            tmp[item.fillDay]
              ? (tmp[item.fillDay].pm = item.maxPef)
              : (tmp[item.fillDay] = { pm: item.maxPef })
          })
        }
        if (res.data && res.data.dv && Array.isArray(res.data.dv)) {
          res.data.dv.forEach((item) => {
            // endValue.push(item.maxPef)
            tmp[item.fillDay]
              ? (tmp[item.fillDay].dv = item.maxDiurnalVariability)
              : (tmp[item.fillDay] = { dv: item.maxDiurnalVariability })
          })
        }
        Object.keys(tmp).forEach((key) => {
          xAxis.push(key)
          const { am, pm, dv } = tmp[key]
          startValue.push(am)
          endValue.push(pm)
          dvValue.push(dv)
        })
        pageData.chartData = { xAxis, startValue, endValue, dvValue }
        console.log('res =' + JSON.stringify(res))
      }
      // 表格数据
      const chartTypeChange = function (label) {
        console.log('chartTypeChange =' + label)
        timeRang.value = [pageData.search.start, pageData.search.end]
        if (label === '列表') {
          loadData(pageData.search)
        } else {
          loadPefCharData(pageData.search)
        }
      }
      const paginaChange = function (params) {
        pageData.search.pageIndex = params.current
        pageData.search.pageSize = params.pageSize
        pageData.search.orderType = params.orderType
        loadData(pageData.search)
      }
      const valF = function (rule, value, cb) {
        console.log('valF = ' + JSON.stringify(value))
        let patten = /^[+-]?(0|([1-9]\d*))(\.\d+)?$/g
        if (value && patten.test(value)) {
          return true
        } else {
          return cb('必须为数字或小数')
        }
      }
      const rules = {
        submitTime: [
          { required: true, trigger: 'input', message: '请选择时间' },
        ],
        pef1: [{ required: true, validator: valF, trigger: 'input' }],
        pef2: [{ required: true, validator: valF, trigger: 'input' }],
        pef3: [{ required: true, validator: valF, trigger: 'input' }],
      }
      const { to } = usePromise()
      const onSubmit = function () {
        dialogRef.value.validate(async (valid) => {
          if (valid) {
            const loading = ElLoading.service()
            const [err, preRes] = await to(
              getInitPef({ patientId: route.query.id })
            )
            if (err) {
              ElMessage.error(preRes.message)
              return
            }
            pageData.form['patientId'] = route.query.id
            console.log(
              'diurnalVariability = ' + preRes.data.diurnalVariability
            )
            pageData.form['diurnalVariability'] = preRes.data.diurnalVariability
            const nextRes = await savePef(pageData.form).catch(() => {
              loading.close()
            })
            isVisble.value = false
            loading.close()
            // 刷新图表
            chartTypeChange(radioActive.value)
            ElMessage.success(nextRes.message)
          }
        })
      }
      return {
        pageData,
        activeIndex,
        handleSelect,
        record,
        chartTypeChange,
        radioActive,
        paginaChange,
        rules,
        isVisble,
        onSubmit,
        dialogRef,
        timeRang,
        timeChange,
      }
    },
  }
</script>
<style lang="scss" scoped>
  .patientTrack-container {
    .el-descriptions__header {
      height: 40px;
      margin-bottom: 0px;
    }
    .el-menu-item {
      height: 40px;
      line-height: 40px;
    }
    .emrChart-content {
      margin-top: 20px;
      padding: 0 20px;
      overflow: hidden;
      .hubs {
        margin-bottom: 20px;
        display: flex;
        justify-items: center;
        align-content: space-between;
        .el-button {
          vertical-align: middle;
          float: right;
        }

        .search-grip {
          // padding: 10px;
          display: inline-block;
          // display: flex;
          // align-items: center;
          span {
            white-space: nowrap;
          }
          .el-input {
            display: inline-block;
            margin-left: 10px;
            // vertical-align: middle;
          }
          .el-select {
            margin-left: 10px;
          }
          :deep(.el-date-editor) {
            margin-left: 10px;
          }
        }
      }
    }
  }
</style>
